package com.sunmnet.auto.spring.mvc;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import com.sunmnet.pub.conf2.MultipleUtilityConf;
import com.sunmnet.pub.conf2.XMLUtils;
import com.sunmnet.pub.connector.log.LogUtils;
import org.slf4j.LoggerFactory;

public class ASMConfig {

	/** 全局ID */
	public final static String ID = "auto-spring-mvc";

	/** 数据源ID */
	public final static String DS = "auto-spring-mvc";

	/** 工程配置文件 */
	private String confPath = System.getProperty("user.dir") + File.separator
			+ "conf" + File.separator + "auto-spring-mvc_conf.xml";

	/** 配置文件路径  */
	private String appPath = System.getProperty("user.dir") + File.separator
			+ "conf" + File.separator + "auto-spring-mvc_conf.xml";

	/** LOG  */
	private final static org.slf4j.Logger LOG = org.slf4j.LoggerFactory
			.getLogger(ASMConfig.class);

	/** 配置文件对象 */
	private MultipleUtilityConf muc = new MultipleUtilityConf(ID);

	/** 单例  */
	private static ASMConfig config = null;

	private final static String logFilePath = System.getProperty("user.dir") + File.separator
			+ "conf" + File.separator + "logback.xml";

	private final static String logFilePath2 = System.getProperty("user.dir") + File.separator
			+ "power-db-auto-code" + File.separator + "conf" + File.separator + "logback.xml";

	/** 私有构造方法  */
	private ASMConfig() {
		String path = logFilePath;
		if (!new File(logFilePath).isFile()) {
			path = logFilePath2;
		}

		LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
		JoranConfigurator configurator = new JoranConfigurator();
		configurator.setContext(lc);
		lc.reset();

		try {
			configurator.doConfigure(path);
		} catch (Exception var4) {
			var4.printStackTrace();
		}
		LOG.info("\r\n" + new Version().getPrint());
		init();
	}

	/**
	 * 单例
	 * @return 单例对象
	 */
	public static ASMConfig getInstance() {
		if (config == null) {
			synchronized (ASMConfig.class) {
				if (config == null) {
					config = new ASMConfig();
				}
			}
		}
		return config;
	}

	/** 初始化配置  */
	private void init() {
		loadXML(appPath, confPath);
		loadDB(DS);
	}

	/**
	 * 加载数据配置
	 *
	 * @param dsID
	 */
	private void loadDB(String dsdsID) {
		//TODO 
	}
	
	/** 表名数组  */
	private String[] tableArray = null;
	
	/** 表名前缀数组  */
	private String[] tablePreArray = null;
	
	/** 分类目录名称  */
	private String typeDir = null;
	
	/** 执行方式，1数据库 2pdm  */
	private int doType = 1;
	
	/** pdm文件路径  */
	private String pdmPath = null;

	/**
	 * 初始化XML配置
	 *
	 * @param appPath	开发配置文件路径
	 * @param confPath	工程配置文件路径
	 */
	private void loadXML(String appPath, String confPath) {
		try {
			//			muc.addXMLFile(appPath);
			muc.addXMLFile(confPath);
		} catch (DocumentException e) {
			LOG.error("load xml file error, system exit", e);
			System.exit(1);
		}
		
		String tablePres = null;
		//String tableNames = null;
		//tableNames = muc.getBaseValue(ID, "tableNames");
		tablePres = muc.getBaseValue(ID, "tablePres");
		
		setPdmPath(muc.getBaseValue(ID, "pmdPath", ""));
		setDoType(muc.getBaseValue(ID, "doType", 1));
		// setTableArray(tableNames.split(","));
		setTablePreArray(tablePres.split(","));
		setTypeDir(muc.getBaseValue(ID, "typeDir", ""));
		
		readPackages(confPath);
		
		LOG.info("load XML success");
	}
	@SuppressWarnings("unchecked")
	private void readPackages(String confPath){
		Document doc = null;
		try {
			doc = XMLUtils.readXMLPath(confPath);
		} catch (DocumentException e) {
			LOG.error("load xml file error, system exit", e);
			System.exit(1);
		}
		List<Element> list = doc.getRootElement().elements();
		for (int i = 0; i < list.size(); i++) {
			Element e = list.get(i);
			if("bases".equalsIgnoreCase(e.getName())){
				List<Element> ele = e.elements();
				for (Element element : ele) {
					// 在这里就只当 auto-spring-mvc_config.xml 里面只有一个 base
					if(element.getName().equalsIgnoreCase("base")){
						setPackageAndTables(element.elements());
					}
				}
			}
		}
	}
	
	public static String CLASS_PATH="";
	public static String BASE_PATH="";
	public static String BASE_JAP_PATH = "";
	public static Map<String, String> TABLE_PACKAGE_MAP = new HashMap<String, String>();
	
	@SuppressWarnings("unchecked")
	private void setPackageAndTables(List<Element> list){
		for(int i=0; i< list.size(); i++){
			Element e = list.get(i);
			System.out.println(e.getName());
			if(e.getName().equalsIgnoreCase("baseJavaPath")){
				// 设置 base package
				CLASS_PATH = e.getTextTrim();
			// 取得表
			}else if(e.getName().equalsIgnoreCase("baseJspPath")){
				// 设置 base package
				BASE_JAP_PATH = e.getTextTrim();
			// 取得表
			}else if(e.getName().equalsIgnoreCase("basePath")){
				// 设置 base package
				BASE_PATH = e.getTextTrim();
			// 取得表
			}else if(e.getName().equalsIgnoreCase("packages")){
				List<Element> elements = e.elements();
				setTables(elements);
			}
		}
	}
	@SuppressWarnings("unchecked")
	private void setTables(List<Element> list){
		String p = "";
		for(int i=0; i< list.size(); i++){
			List<Element> pl = list.get(i).elements();
			for(int k=0; k< pl.size(); k++){
				Element element = pl.get(k);
				if(element.getName().equalsIgnoreCase("path")){
					p = element.getTextTrim();
				}
			}
			
			for(int k=0; k< pl.size(); k++){
				Element element = pl.get(k);
				if(element.getName().equalsIgnoreCase("tableNames")){
					String[] arr = element.getTextTrim().split(",");
					for (String s : arr) {
						TABLE_PACKAGE_MAP.put(s.trim(), p==null?"":p.trim());
					}
				}
			}
		}
		Object[] array = TABLE_PACKAGE_MAP.keySet().toArray();
		String[] arr = new String[array.length];
		for(int i=0; i< array.length; i++){
			arr[i] = array[i]+"";
		}
		setTableArray(arr);
	}
	
	/**
	 * 简单测试
	 *
	 * @param args
	 */
	public static void main(String[] args) {
		ASMConfig.getInstance();
	}

	/**
	 * GET confPath
	 * @return the confPath
	 */
	public String getConfPath() {
		return confPath;
	}

	/**
	 * SET confPath
	 * @param confPath the confPath to set
	 */
	public void setConfPath(String confPath) {
		this.confPath = confPath;
	}

	/**
	 * GET muc
	 * @return the muc
	 */
	public MultipleUtilityConf getMuc() {
		return muc;
	}

	/**
	 * SET muc
	 * @param muc the muc to set
	 */
	public void setMuc(MultipleUtilityConf muc) {
		this.muc = muc;
	}

	/**
	 * tableArray
	 * @return the tableArray
	 */
	public String[] getTableArray() {
		return tableArray;
	}

	/**
	 * tableArray
	 * @param tableArray the tableArray to set
	 */
	public void setTableArray(String[] tableArray) {
		this.tableArray = tableArray;
	}

	/**
	 * tablePreArray
	 * @return the tablePreArray
	 */
	public String[] getTablePreArray() {
		return tablePreArray;
	}

	/**
	 * tablePreArray
	 * @param tablePreArray the tablePreArray to set
	 */
	public void setTablePreArray(String[] tablePreArray) {
		this.tablePreArray = tablePreArray;
	}

	/**
	 * typeDir
	 * @return the typeDir
	 */
	public String getTypeDir() {
		return typeDir;
	}

	/**
	 * typeDir
	 * @param typeDir the typeDir to set
	 */
	public void setTypeDir(String typeDir) {
		this.typeDir = typeDir;
	}

	/**
	 * doType
	 * @return the doType
	 */
	public int getDoType() {
		return doType;
	}

	/**
	 * doType
	 * @param doType the doType to set
	 */
	public void setDoType(int doType) {
		this.doType = doType;
	}

	public String getPdmPath() {
		return pdmPath;
	}

	public void setPdmPath(String pdmPath) {
		this.pdmPath = pdmPath;
	}

}